package com.example.main;

import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.main.ukey.InputAsyncTask;
import com.example.main.ukey.OTG_KEY;
import com.example.main.ukey.SearchAsyncTask;
import com.example.main.ukey.Tool;
import com.example.main.ukey.ZhiWenUtils;


public class ZhiwenActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "ZhiwenActivity";
    private Button btn_open;
    private Button btn_close;
    private Button btn_clear;
    private Button btn_input;
    private Button btn_search;
    private EditText ed_zhiwen;
    private UsbManager mUsbManager;
    private UsbDevice mDevice;
    private OTG_KEY msyUsbKey;
    private int mhKey = 0;
    private int fingerCnt = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhiwen);
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);// 启动服务进程
        btn_open = findViewById(R.id.btn_open);
        btn_close = findViewById(R.id.btn_close);
        btn_clear = findViewById(R.id.btn_clear);
        btn_input = findViewById(R.id.btn_input);
        btn_search = findViewById(R.id.btn_search);
        ed_zhiwen = findViewById(R.id.ed_zhiwen);
        btn_open.setOnClickListener(this);
        btn_close.setOnClickListener(this);
        btn_clear.setOnClickListener(this);
        btn_input.setOnClickListener(this);
        btn_search.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_open:
                openZhiWenMachine();
                break;
            case R.id.btn_close:
                closeZhiwenMachine();
                break;
            case R.id.btn_clear:
                clearZhiwenMachine();
                break;
            case R.id.btn_input:
                fingerCnt = Integer.parseInt(ed_zhiwen.getText().toString());
                inputZhiWenMachine();
                break;
            case R.id.btn_search:
                serachZhiWenMacine();
                break;
        }
    }

    /**
     * 查询指纹
     */
    private void serachZhiWenMacine() {
        SearchAsyncTask searchAsyncTask = new SearchAsyncTask(this, msyUsbKey);
        searchAsyncTask.execute(1);
    }

    /**
     * 录入指纹
     */
    private void inputZhiWenMachine() {
        //getZhiwenMachineInfo();
        if (fingerCnt >= 1000) {
            Log.i(TAG, "指纹库已满，请删除");
            return;
        }

        InputAsyncTask asyncTask = new InputAsyncTask(this, msyUsbKey, fingerCnt);
        asyncTask.execute(1);
    }

    /**
     * 清空指纹
     */
    private void clearZhiwenMachine() {
        if (ZhiWenUtils.PS_OK != msyUsbKey.PSEmpty(ZhiWenUtils.DEV_ADDR)) {
            Log.i(TAG, "清空指纹库失败");
        }
        fingerCnt = 0;
        Log.i(TAG, "清空指纹库成功");
    }

    /**
     * 开启指纹机器
     */
    private void openZhiWenMachine() {
        for (UsbDevice device : mUsbManager.getDeviceList().values()) {
            if (0x2109 == device.getVendorId() && 0x7638 == device.getProductId()) {
                mDevice = device;
                Log.i(TAG, "find this usb device vID:0x2109");
                break;
            }
        }

        if (mDevice == null) {
            Log.i(TAG, "can't find this device!");
            return;
        }

        if (!mUsbManager.hasPermission(mDevice)) {
            Log.i(TAG, "no Permission!");
            return;
        }

        try {
            msyUsbKey = null;
            msyUsbKey = new OTG_KEY(mUsbManager, mDevice);
            int key[] = new int[1];
            int ret = msyUsbKey.UsbOpen();
            if (ret == OTG_KEY.DEVICE_SUCCESS) {
                mhKey = key[0];
                Log.i(TAG, "open device success hkey :" + Tool.int2HexStr(mhKey));
            } else {
                Log.i(TAG, "open device fail errocde :" + ret);//Tool.int2HexStr(ret));
            }
        } catch (Exception e) {
            Log.i(TAG, "Exception: => " + e.toString());
            return;
        }

        int ret;
        if ((ret = msyUsbKey.PSword()) != 0) {
            Log.i(TAG, "密码验证错误" + ret);
            return;
        }
        getZhiwenMachineInfo();
    }

    /**
     * 获取设备信息
     */
    private void getZhiwenMachineInfo() {
        int[] indexMax = new int[1];
        int[] len = new int[1];
        int[] index = new int[256];
        if (0 != ZhiWenUtils.getUserContent(msyUsbKey, indexMax, index, len)) {
            Log.i(TAG, "获取设备信息失败");
            return;
        }
        if (len[0] == 0) {
            Log.i(TAG, "从第" + indexMax[0] + "个ID开始存储指纹");
            fingerCnt = 0;
        } else {
            indexMax[0]++;
            Log.i(TAG, "从第" + indexMax[0] + "个ID开始存储指纹");
            fingerCnt = indexMax[0];
        }
    }

    /**
     * 关闭指纹设备
     */
    private void closeZhiwenMachine() {
        try {
            Log.i(TAG, "设备已关闭");
            msyUsbKey.CloseCard(mhKey);
        } catch (Exception e) {
            Log.i(TAG, "Exception: => " + e.toString());
            return;
        }
    }

}
